package app1.rapidsquare.com.activity;

import android.content.Intent;
import android.content.IntentSender;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.core.ILoadComplete;
import app1.rapidsquare.com.database.AgileSyncService;
import app1.rapidsquare.com.database.AgileUserProvider;

public class SocialActivity extends AgileActivity implements ILoadComplete {

    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private UiLifecycleHelper uiHelper;
    private static final List<String> permissions = Arrays.asList(
            "user_about_me", "email", "user_birthday", "user_status",
            "user_location", "user_online_presence", "user_hometown",
            "user_photo_video_tags", "user_photos", "offline_access",
            "user_website");

    private GoogleApiClient mGoogleApiClient;
    private ConnectionResult mConnectionResult;
    private boolean mIntentInProgress;
    private boolean mSignInClicked;
    private TextView mTextViewInternetConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(this, null);
        uiHelper.onCreate(savedInstanceState);

        setContentView(R.layout.activity_social);

        mTextViewInternetConnection = (TextView) findViewById(R.id.textViewInternetConnection);
        mTextViewInternetConnection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTextViewInternetConnection.setVisibility(View.GONE);
            }
        });

        LinearLayout mLinearLayoutEmail = (LinearLayout) findViewById(R.id.linearLayoutEmail);
        mLinearLayoutEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SocialActivity.this, LoginActivity.class);
                startActivityForResult(intent, Utility.LOGIN_ACTIVITY_REQUEST_CODE);
            }
        });

        LinearLayout mLinearLayoutGooglePlus = (LinearLayout) findViewById(R.id.linearLayoutGooglePlus);
        mLinearLayoutGooglePlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (IsAvailableInternet()) {
                    mTextViewInternetConnection.setVisibility(View.GONE);
                    if (!mGoogleApiClient.isConnecting()) {
                        mGoogleApiClient.connect();
                        mSignInClicked = true;
                        resolveSignInError();
                    }
                } else {
                    mTextViewInternetConnection.setVisibility(View.VISIBLE);
                }
            }
        });

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(connectionCallBack)
                .addOnConnectionFailedListener(onConnectionFailedListener).addApi(Plus.API, null)
                .addScope(Plus.SCOPE_PLUS_PROFILE).build();

        LinearLayout mLinearLayoutLinkedIn = (LinearLayout) findViewById(R.id.linearLayoutLinkedIn);
        mLinearLayoutLinkedIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (IsAvailableInternet()) {
                    mTextViewInternetConnection.setVisibility(View.GONE);
                    Intent intent = new Intent(SocialActivity.this, WebViewActivity.class);
                    startActivityForResult(intent, Utility.LINKED_IN_DATA_ACTIVITY_REQUEST_CODE);
                } else {
                    mTextViewInternetConnection.setVisibility(View.VISIBLE);
                }
            }
        });

        LinearLayout mLinearLayoutFacebook = (LinearLayout) findViewById(R.id.linearLayoutFacebook);
        mLinearLayoutFacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (IsAvailableInternet()) {
                    mTextViewInternetConnection.setVisibility(View.GONE);
                    Session.openActiveSession(SocialActivity.this, true,
                            permissions, callback);
                } else {
                    mTextViewInternetConnection.setVisibility(View.VISIBLE);
                }
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();

        if (checkPlayServices()) {
            getRegId();
        } else {
            Utility.Info("No valid Google Play Services APK found.", "");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        uiHelper.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Session.getActiveSession() != null) {
            Session.getActiveSession().onActivityResult(this, requestCode,
                    resultCode, data);
        }
        if (requestCode == Utility.GOOGLE_PLUS_REQUEST_CODE) {
            if (resultCode != RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }

        if (requestCode == Utility.LOGIN_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.hasExtra(Utility.LOGIN_INTENT_DATA_NAME)) {
            try {
                User user = (User) data.getSerializableExtra(Utility.LOGIN_INTENT_DATA_NAME);
                setResult(RESULT_OK, new Intent().putExtra(Utility.SOCIAL_INTENT_DATA_NAME, user));
                Utility.setUserSession(getApplicationContext(), user);
                if (mProgressDialog != null)
                    mProgressDialog.show();
                Utility.AgileSyncUpdater(new AgileUserProvider(getApplicationContext()), this);
            } catch (Exception ex) {
                Utility.Log("Login user is null in SocialActivity", ex);
            }

        }
        if (requestCode == Utility.LINKED_IN_DATA_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.hasExtra(Utility.LINKED_IN_INTENT_DATA_NAME)) {
            try {
                User user = (User) data.getSerializableExtra(Utility.LINKED_IN_INTENT_DATA_NAME);
                getIntent().putExtra(Utility.SOCIAL_TEMP_INTENT_DATA_NAME, user);
                LoginSocialNetworks(user);

            } catch (Exception ex) {
                Utility.Log("Linked user is null in SocialActivity", ex);
            }
        }
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                finish();
            }
            return false;
        }
        return true;
    }

    public void getRegId() {

        if (IsAvailableInternet()) {
            String regId = "";
            if (Utility.getUserSession(getApplicationContext()) != null)
                regId = Utility.getUserSession(getApplicationContext()).DeviceId;

            if (Utility.isNullOrEmpty(regId)) {
                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(Void... params) {
                        String regid = "";
                        try {
                            GoogleCloudMessaging gcm = GoogleCloudMessaging
                                    .getInstance(getApplicationContext());

                            regid = gcm
                                    .register(Utility.GOOGLE_CLOUD_SERVICE_PROJECT_NUMBER);

                        } catch (IOException e) {
                            Utility.Log("get google reg Id", e);

                        }
                        return regid;
                    }

                    @Override
                    protected void onPostExecute(String msg) {
                        if (!Utility.isNullOrEmpty(msg)) {
                            User profileData;
                            if (Utility.getUserSession(getApplicationContext()) != null)
                                profileData = Utility.getUserSession(getApplicationContext());
                            else
                                profileData = new User();

                            profileData.DeviceId = msg;
                            Utility.setUserSession(getApplicationContext(), profileData);
                        }
                    }
                }.execute(null, null, null);
            }
        }
    }

    @Override
    protected void getResponce(String result) {
        if (!Utility.isNullOrEmpty(result)) {
            JSONObject resultJsonObject;
            try {
                resultJsonObject = new JSONObject(result);

                if (resultJsonObject.has("Error")) {
                    String error = resultJsonObject.getString("Error");
                    if (Utility.isNullOrEmpty(error)) {

                        String resultObject = resultJsonObject
                                .getString("Result");
                        User userDetails = Utility.Deserialize(User.class, resultObject);

                        if (!Utility.isNullOrEmpty(userDetails.UserToken)) {
                            User userInCache = new User();
                            if (getIntent().hasExtra(Utility.SOCIAL_TEMP_INTENT_DATA_NAME)) {
                                userInCache = (User) getIntent().getSerializableExtra(Utility.SOCIAL_TEMP_INTENT_DATA_NAME);
                            }

                            userInCache.DeviceId = Utility.getUserSession(getApplicationContext()).DeviceId;
                            userInCache.UserToken = userDetails.UserToken;
                            userInCache.Id = userDetails.Id;
                            userInCache.Code = userDetails.Code;
                            userInCache.SocialType = userDetails.SocialType;
                            Utility.setUserSession(getApplicationContext(), userInCache);

                            setResult(RESULT_OK, new Intent().putExtra(Utility.SOCIAL_INTENT_DATA_NAME, userInCache));
                            if (mProgressDialog != null)
                                mProgressDialog.show();

                            Utility.AgileSyncUpdater(new AgileUserProvider(getApplicationContext()), this);
                        }
                    } else {
                        Toast.makeText(SocialActivity.this, "Error in connection to server", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (JSONException e) {
                Utility.Log("getResponce error convert json to user in SocialActivity ", e);
            }
        } else {
            Toast.makeText(SocialActivity.this, "Error in connection to server", Toast.LENGTH_SHORT).show();
        }
    }

    // Google Plus

    private void resolveSignInError() {
        if (mConnectionResult != null && mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, Utility.GOOGLE_PLUS_REQUEST_CODE);
            } catch (IntentSender.SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        } else
            mGoogleApiClient.connect();
    }

    private GoogleApiClient.ConnectionCallbacks connectionCallBack = new GoogleApiClient.ConnectionCallbacks() {
        @Override
        public void onConnected(Bundle bundle) {
            mSignInClicked = false;
            getProfileInformation();
        }

        @Override
        public void onConnectionSuspended(int i) {
            mGoogleApiClient.connect();
        }
    };

    private OnConnectionFailedListener onConnectionFailedListener = new OnConnectionFailedListener() {
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            if (!connectionResult.hasResolution()) {
                GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), SocialActivity.this,
                        0).show();
                return;
            }

            if (!mIntentInProgress) {
                mConnectionResult = connectionResult;
                if (mSignInClicked) {
                    resolveSignInError();
                }
            }
        }
    };

    private void getProfileInformation() {
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person currentPerson = Plus.PeopleApi
                        .getCurrentPerson(mGoogleApiClient);

                if (currentPerson != null && currentPerson.isPlusUser()) {
                    User user = new User();
                    user.GooglePlusId = currentPerson.getId();
                    user.Email = Plus.AccountApi.getAccountName(mGoogleApiClient);
                    String personName = currentPerson.getDisplayName();
                    user.FirstName = personName.split(" ")[1];
                    user.LastName = personName.split(" ")[0];

                    user.ImageUrl = currentPerson.getImage().getUrl();
                    user.SocialType = Utility.SocialType.GooglePlus.value;
                    user.GooglePlusName = user.FirstName + " " + user.LastName;
                    getIntent().putExtra(Utility.SOCIAL_TEMP_INTENT_DATA_NAME, user);
                    LoginSocialNetworks(user);
                } else
                    Toast.makeText(SocialActivity.this, getString(R.string.is_not_google_plus), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Utility.Log("get google plus profile information ", e);
        }
    }

    // Facebook

    private Session.StatusCallback callback = new Session.StatusCallback() {

        @Override
        public void call(Session session, SessionState state,
                         Exception exception) {
            if (session.isOpened()) {
                SendRequestToFacebook(session);
            }
        }
    };

    private void SendRequestToFacebook(Session session) {
        mProgressDialog.show();
        Request uploadRequest = Request.newMeRequest(session,
                new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        DeserializeAndSave(user);
                        mProgressDialog.dismiss();
                    }
                });
        uploadRequest.executeAsync();
    }

    private void DeserializeAndSave(GraphUser graphUser) {
        if (graphUser != null) {
            try {
                JSONObject jsonObject = graphUser.getInnerJSONObject();
                User user = new User();

                if (jsonObject.has("id"))
                    user.FacebookId = jsonObject.getString("id");
                if (jsonObject.has("first_name"))
                    user.FirstName = jsonObject.getString("first_name");
                if (jsonObject.has("last_name"))
                    user.LastName = jsonObject.getString("last_name");
                if (jsonObject.has("email"))
                    user.Email = jsonObject.getString("email")
                            .replace('"', ' ').trim();
                if (jsonObject.has("location")) {
                    JSONObject jLocationObject = new JSONObject(
                            jsonObject.getString("location"));
                    if (jLocationObject.has("name")) {
                        String locationName = jLocationObject.getString("name");
                        user.City = locationName.split(",")[0];
                        user.State = locationName.split(",")[0];
                    }
                }

                user.ImageUrl = String.format(Utility.FACEBOOK_PROFILE_PIC_URL_FORMAT, user.FacebookId);
                user.SocialType = Utility.SocialType.Facebook.value;
                user.FacebookName = user.FirstName + " " + user.LastName;
                getIntent().putExtra(Utility.SOCIAL_TEMP_INTENT_DATA_NAME, user);
                LoginSocialNetworks(user);

            } catch (Exception e) {
                Utility.Log("Facebook login deserialize", e);
            }
        }
    }

    private void LoginSocialNetworks(User accountData) {
        try {
            User userSession = Utility.getUserSession(getApplicationContext());
            String deviceId = "";
            if (userSession != null) {
                deviceId = userSession.DeviceId;
                Utility.setUserSession(getApplicationContext(), userSession);
            }

            User user = new User();
            user.Email = accountData.Email;
            user.SocialType = accountData.SocialType;
            user.IsCheck = accountData.SocialType == Utility.SocialType.Email.value;
            user.DeviceOs = 1;
            user.DeviceId = deviceId;
            user.MobileWorkingSystem = 2;
            String jsonResult = Utility.Serialize(user)
                    .toString();
            setUrl(Utility.LOGIN_URL);
            setRequestMethodType(Utility.RequestMethodType.POST);
            mHttpEntity = new StringEntity(jsonResult);
            SendRequest(true);

        } catch (Exception ex) {
            Utility.Log("LoginSocialNetworks in SocialActivity", ex);
        }
    }


    @Override
    public void onLoadComplete(User user) {
        RunSyncService();
        Intent intent = new Intent(Utility.NOTIFICATION_BROADCASTRECEIVER_ACTION);
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        finish();
    }

    private void RunSyncService() {
        Intent serviceIntent = new Intent(getApplicationContext(), AgileSyncService.class);
        startService(serviceIntent);
    }
}
